<template>
    <div class="rsa-container">
        <div class="control-panel">
            <div class="options-panel">
                <div class="key-section">
                    <div class="key-input">
                        <n-tabs class="key-tabs" v-model:value="activeTab">
                            <n-tab-pane name="generate" tab="生成密钥对">
                                <div class="generate-panel">
                                    <n-select v-model:value="keySize" :options="keySizeOptions" class="size-select" />
                                    <n-button type="primary" @click="generateKeyPair">
                                        生成密钥对
                                    </n-button>
                                </div>
                                <div class="key-display" v-if="keyPair.publicKey">
                                    <div class="key-field">
                                        <div class="field-header">
                                            <span>公钥:</span>
                                            <n-button quaternary size="small" @click="copyPublicKey">
                                                复制
                                            </n-button>
                                        </div>
                                        <n-input v-model:value="keyPair.publicKey" type="textarea" readonly />
                                    </div>
                                    <div class="key-field">
                                        <div class="field-header">
                                            <span>私钥:</span>
                                            <n-button quaternary size="small" @click="copyPrivateKey">
                                                复制
                                            </n-button>
                                        </div>
                                        <n-input v-model:value="keyPair.privateKey" type="textarea" readonly />
                                    </div>
                                </div>
                            </n-tab-pane>
                            <n-tab-pane name="input" tab="输入密钥">
                                <div class="key-input-panel">
                                    <div class="key-field">
                                        <div class="field-header">
                                            <span>{{ mode === 'encrypt' ? '公钥:' : '私钥:' }}</span>
                                            <n-button quaternary size="small" @click="clearKey">
                                                清空
                                            </n-button>
                                        </div>
                                        <n-input v-model:value="inputKey" type="textarea"
                                            :placeholder="mode === 'encrypt' ? '请输入公钥' : '请输入私钥'" />
                                    </div>
                                </div>
                            </n-tab-pane>
                        </n-tabs>
                    </div>
                </div>
                <div class="mode-options" v-if="activeTab === 'input'">
                    <n-radio-group v-model:value="mode">
                        <n-radio-button key="encrypt" value="encrypt">加密</n-radio-button>
                        <n-radio-button key="decrypt" value="decrypt">解密</n-radio-button>
                    </n-radio-group>
                </div>
            </div>
            <n-button @click="clearAll">清空</n-button>
        </div>

        <div class="content-panel" v-if="activeTab === 'input'">
            <!-- 输入区域 -->
            <div class="input-section">
                <div class="section-header">
                    <span>输入</span>
                    <div class="actions">
                        <n-button quaternary size="small" @click="clearInput">
                            清空
                        </n-button>
                    </div>
                </div>
                <n-input v-model:value="inputText" type="textarea" :autosize="{ minRows: 5, maxRows: 10 }"
                    :placeholder="mode === 'encrypt' ? '请输入要加密的文本' : '请输入要解密的文本'" />
            </div>

            <!-- 转换按钮 -->
            <div class="action-panel">
                <n-button type="primary" @click="processText" :disabled="!canProcess">
                    {{ mode === 'encrypt' ? '加密' : '解密' }}
                </n-button>
            </div>

            <!-- 输出区域 -->
            <div class="output-section">
                <div class="section-header">
                    <span>输出</span>
                    <div class="actions">
                        <n-button quaternary size="small" @click="copyOutput" :disabled="!outputText">
                            复制
                        </n-button>
                        <n-button quaternary size="small" @click="clearOutput" :disabled="!outputText">
                            清空
                        </n-button>
                    </div>
                </div>
                <n-input v-model:value="outputText" type="textarea" :autosize="{ minRows: 5, maxRows: 10 }" readonly
                    placeholder="处理结果将显示在这里" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import JSEncrypt from 'jsencrypt'
import view from '@renderer/util/ui/ViewUtil'

// 添加标签页激活状态
const activeTab = ref('generate')

// 加解密选项
const mode = ref<'encrypt' | 'decrypt'>('encrypt')
const keySize = ref<1024 | 2048>(2048)
const inputKey = ref('')
const inputText = ref('')
const outputText = ref('')

// 密钥对
const keyPair = ref<{
    publicKey: string
    privateKey: string
}>({
    publicKey: '',
    privateKey: ''
})

// 密钥长度选项
const keySizeOptions = [
    { label: '1024 位', value: 1024 },
    { label: '2048 位', value: 2048 }
]

// 是否可以处理
const canProcess = computed(() => {
    return inputKey.value && inputText.value.trim().length > 0
})

// 生成密钥对
const generateKeyPair = () => {
    const encrypt = new JSEncrypt({ default_key_size: keySize.value.toString() })
    keyPair.value = {
        publicKey: encrypt.getPublicKey() || '',
        privateKey: encrypt.getPrivateKey() || ''
    }
}

// 处理文本
const processText = () => {
    if (!canProcess.value) {
        if (!inputKey.value) {
            view.alertErrorMessage(mode.value === 'encrypt' ? '请输入公钥' : '请输入私钥')
        } else {
            view.alertErrorMessage('请输入要处理的文本')
        }
        return
    }

    try {
        const encrypt = new JSEncrypt()

        if (mode.value === 'encrypt') {
            encrypt.setPublicKey(inputKey.value)
            const encrypted = encrypt.encrypt(inputText.value)
            if (!encrypted) throw new Error('加密失败')
            outputText.value = encrypted
        } else {
            encrypt.setPrivateKey(inputKey.value)
            const decrypted = encrypt.decrypt(inputText.value)
            if (!decrypted) throw new Error('解密失败')
            outputText.value = decrypted
        }
    } catch (error) {
        view.alertErrorMessage(mode.value === 'encrypt' ? '加密失败' : '解密失败')
        console.error('RSA处理失败:', error)
    }
}

// 复制公钥
const copyPublicKey = async () => {
    try {
        await navigator.clipboard.writeText(keyPair.value.publicKey)
        view.alertSuccessMessage('复制公钥成功')
    } catch (error) {
        view.alertErrorMessage('复制失败')
    }
}

// 复制私钥
const copyPrivateKey = async () => {
    try {
        await navigator.clipboard.writeText(keyPair.value.privateKey)
        view.alertSuccessMessage('复制私钥成功')
    } catch (error) {
        view.alertErrorMessage('复制失败')
    }
}

// 复制输出
const copyOutput = async () => {
    try {
        await navigator.clipboard.writeText(outputText.value)
        view.alertSuccessMessage('复制成功')
    } catch (error) {
        view.alertErrorMessage('复制失败')
    }
}

// 清空密钥
const clearKey = () => {
    inputKey.value = ''
    clearInput()
}

// 清空输入
const clearInput = () => {
    inputText.value = ''
    outputText.value = ''
}

// 清空输出
const clearOutput = () => {
    outputText.value = ''
}

// 清空所有
const clearAll = () => {
    keyPair.value = { publicKey: '', privateKey: '' }
    clearKey()
}

// 监听标签页变化
watch(activeTab, () => {
    clearInput()
    inputKey.value = ''
})
</script>

<style scoped>
.rsa-container {
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 16px;
    overflow-y: auto;
}

.control-panel {
    display: flex;
    gap: 16px;
    padding: 16px;
    border: 1px solid var(--border-color);
    border-radius: 4px;
    align-items: flex-start;
}

.options-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.key-section {
    display: flex;
    gap: 16px;
    align-items: flex-start;
}

.generate-panel {
    display: flex;
    gap: 16px;
    align-items: center;
    margin-bottom: 16px;
}

.size-select {
    width: 120px;
}

.key-display,
.key-input-panel {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.key-field {
    display: flex;
    flex-direction: column;
    gap: 8px;
    width: 100%;
}

.key-field :deep(.n-input) {
    width: 100%;
}

.key-field :deep(.n-input-wrapper) {
    width: 100%;
}

.field-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.content-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 16px;
    min-height: 0;
}

.input-section,
.output-section {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.actions {
    display: flex;
    gap: 8px;
}

.action-panel {
    display: flex;
    justify-content: center;
    padding: 16px 0;
}

.mode-options {
    display: flex;
    align-items: center;
    gap: 8px;
}

.key-input {
    width: 100%;
}

.key-tabs {
    width: 100%;
}
</style>